package com.heima.common.filter;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AppJwtUtil implements GlobalFilter, Ordered {

    /**
     * 过滤器的执行逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path = request.getURI().getPath();
        //进行判断(如果包含)
        if (path.contains("/exlogin")){
            //放行
            return chain.filter(exchange);
        }
        //获取头中的token
        String token = request.getHeaders().getFirst("token");
        //如果token为空
        if (!StringUtils.isEmpty(token)) {
            //解析token
            try {
                Claims  claimsBody = com.heima.common.util.AppJwtUtil.getClaimsBody(token);
                //获取状态码
                int status = com.heima.common.util.AppJwtUtil.verifyToken(claimsBody);
                //判断token是否有效
                if (status == -1 || status == 0) {
                    //获取userId
                    Object userId = claimsBody.get("userId");
//                    放入请求头
                    request.mutate().header("userId", userId.toString());
                    //返回给后端微服务
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                //记录异常log
                log.info(e.getMessage());
            }
        }

        //解析失败,返回401,未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     *过滤器置执行的顺序,数值越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
